
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_user_tag.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///标签
class SearchTag extends StatefulWidget {
  const SearchTag({Key key,}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new SearchTagState();
  }
}

class SearchTagState extends State<SearchTag> {
  SearchTagState();

  HttpRepository httpRepository;
  String pageToken;
  int size = 0;
  bool isLoadedData = false;
  String keyword;


  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscUserTag> list;


  RefreshController controller = RefreshController(initialRefresh: false);
  TextEditingController textEditingController = TextEditingController();


  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
    textEditingController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        buildSearch(),
        Expanded(
            child: SmartRefresher(
              controller: controller,
              onRefresh: refresh,
              onLoading: loadMore,
              enablePullUp: true,
              child: buildListView(),
            )
        )
      ],
    );
  }

  buildSearch(){
    return Container(
      padding: EdgeInsets.all(Dimens.gap_view_normal),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Colors.black26), bottom: BorderSide(color: Colors.black26)),
      ),
      child: ConstrainedBox(
          constraints: BoxConstraints(
            maxHeight: Dimens.view_text_field_height_smaller,
          ),
        child: TextField(
          controller: textEditingController,
          decoration: InputDecoration(
            hintText: "搜索你感兴趣的标签",
            hintStyle: MyTextStyle.HINT,
            contentPadding: EdgeInsets.symmetric(vertical: Dimens.gap_view_small),
            border: buildBorder(),
            disabledBorder: buildBorder(),
            enabledBorder: buildBorder(),
            errorBorder: buildBorder(),
            focusedBorder: buildBorder(),
            prefixIcon: Icon(Icons.search, color: Colors.black26,),
          ),
          textInputAction: TextInputAction.search,
          onSubmitted: (String text){
            keyword = text;
            refresh();
          },
        ),
      ),
    );
  }

  buildBorder(){
    return OutlineInputBorder(
      borderSide: BorderSide(color: Colors.black26),
    );
  }

  buildListView(){
    return ListView.separated(
      shrinkWrap: true,
      primary: false,
      itemBuilder: (BuildContext context, int index) {
        if (size == 0) {
          return NoDataWidget();
        } else {
          return buildListItem(index);
        }
      },
      separatorBuilder: (BuildContext context, int index) {
        return SmallWidgets.buildLine();
      },
      itemCount: isLoadedData && size == 0? 1 : size,
//      physics: scrollPhysics,
    );
  }

  buildListItem(int index){
    OscUserTag item = list.elementAt(index);
    return Container(
      padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_biggest, vertical: Dimens.gap_view_smaller),
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Expanded(
              child: Text(item.name, style: MyTextStyle.USER_LIST_TITLE,),
          ),
          Container(
            width: 80,
            height: Dimens.view_button_height_smaller,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: item.related? Colors.black38 : Colors.lightGreen,
              borderRadius: BorderRadius.all(Radius.circular(Dimens.view_radius_size_smaller))
            ),
            margin: EdgeInsets.symmetric(vertical: Dimens.gap_view_normal),
            child: InkWell(
              onTap: (){
                updateTabRelation(id: item.id, index: index, delete: item.related);
              },
              child: Text(item.related? "取消关注" : "关注标签", style: MyTextStyle.LIST_TAG_BUTTON,),
            ),
          )
        ],
      ),
    );
  }

  refresh() async{
    pageToken = null;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
    await httpRepository.searchTagList(name: keyword, pageToken: pageToken).then((resp){
      isLoadedData = true;
      if(resp != null && resp.success){
        OscBaseListResult result = resp.result;
        if(result != null) {
          List<OscUserTag> tempList = result.items;
          if (pageToken == null) {
            list = tempList;
          } else {
            list.addAll(tempList);
          }
          pageToken = result.nextPageToken;
          size = list?.length ?? 0;
          if (result.requestCount > result.responseCount) {
            controller.loadNoData();
          } else {
            controller.loadComplete();
          }
        }
      }
    });
    if(mounted) {
      setState(() {
        controller.refreshCompleted();
      });
    }
  }

  updateTabRelation({@required int id, @required index, @required bool delete}) async{
    return await httpRepository.updateTagRelation(id: id, delete: delete).then((resp){
      if(resp != null && resp.success){
        bool related = list.elementAt(index).related;
        list.elementAt(index).related = !related;
        size = list?.length??0;
        if(mounted){
          setState(() {
          });
        }
      }
    });
  }

  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}
